package com.rongshu.view.mediaPlayer.service;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;

import com.rongshu.eventbus.OpenAudioPlayUI;
import com.rongshu.eventbus.UpdatePlayUI;
import com.rongshu.utils.Constant;
import com.rongshu.view.mediaPlayer.activity.AudiobookPlayerActivity;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class PlayerService extends Service {
    private int startId;
    private AudioManager mAudioManager;
    private String TAG = "PlayerService";

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        //初始化AudioManager对象
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //申请焦点
        mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        startForeground(1120, new Notification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.startId = startId;
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 焦点变化监听器
     */
    private AudioManager.OnAudioFocusChangeListener mAudioFocusChange = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            UpdatePlayUI updatePlayUI = new UpdatePlayUI();
            updatePlayUI.setState(focusChange);
            EventBus.getDefault().post(updatePlayUI);
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    //长时间丢失焦点
                    LogUtil.d(TAG, "AUDIOFOCUS_LOSS");
                    PlayerManager.getPlayer().pause();
                    //释放焦点
                    mAudioManager.abandonAudioFocus(mAudioFocusChange);
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    //短暂性丢失焦点
                    PlayerManager.getPlayer().pause();
                    LogUtil.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    //短暂性丢失焦点并作降音处理
                    LogUtil.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    //重新获得焦点
                    LogUtil.d(TAG, "AUDIOFOCUS_GAIN");
                    PlayerManager.getPlayer().start();
                    break;
            }
        }
    };

    //接收EventBus post过来的PlayEvent
    @Subscribe
    public void onEvent(PlayEvent playEvent) {
        switch (playEvent.getAction()) {
            case PLAY:
                //申请焦点
                mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
                AudiobookDetailsResponse.ResponseBean eventSong = playEvent.getBean();
                AudiobookDetailsResponse.ResponseBean nowPlaying = PlayerManager.getPlayer().getNowPlaying();
                if (eventSong == null) {
                    LogUtil.d("mediaPlayer -- go on");
                    //如果没有传来音频数据，认为该操作是继续播放
                    PlayerManager.getPlayer().start();
                } else if (nowPlaying != null && eventSong.getId() == nowPlaying.getId()) {
                    LogUtil.d("mediaPlayer -- go on");
                    //如果传过来的音频数据，与正在播放的音频数据相同，认为该操作是继续播放
                    PlayerManager.getPlayer().start();
                } else {
                    LogUtil.d("mediaPlayer -- init");
                    //如果传过来的音频数据，与正在播放的音频数据不同，播放传过来的数据
                    PlayerManager.getPlayer().setQueue(eventSong);
                }
                break;
            case PAUST:
                PlayerManager.getPlayer().pause();
                break;
            case STOP:
                PlayerManager.getPlayer().stop();
                stopSelf(startId);
                break;
            case RESUME:
                PlayerManager.getPlayer().setQueue(playEvent.getBean());
                break;
            case BEFORE:
                PlayerManager.getPlayer().previous();
                break;
            case NEXT:
                PlayerManager.getPlayer().next();
                break;
            case RELEASE:
                PlayerManager.getPlayer().release();
                break;
        }
    }

    @Subscribe
    public void onIntentPlayUI(OpenAudioPlayUI audioPlayUI) {
        Intent intent = new Intent(this, AudiobookPlayerActivity.class);
        intent.putExtra(Constant.INTENT_DATA, audioPlayUI.getId());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        PlayerManager.getPlayer().stop();
        EventBus.getDefault().unregister(this);
        mAudioManager.abandonAudioFocus(mAudioFocusChange);
        super.onDestroy();
    }
}